package com.example.sprintboot.service;

import com.example.sprintboot.entity.Cart;
import com.example.sprintboot.mapper.CartMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService {

    @Resource
    private CartMapper cartMapper;

    // 查询所有购物车记录
    public List<Cart> selectAll() {
        return cartMapper.selectAll();
    }

    // 根据 ID 查询单条购物车记录
    public Cart selectById(Integer id) {
        return cartMapper.selectById(id);
    }

    public void add(Cart cart) {
        System.out.println("add cart: userId=" + cart.getUserId() + ", bookId=" + cart.getBookId());
        Cart exist = cartMapper.selectByUserIdAndBookId(cart.getUserId(), cart.getBookId());
        System.out.println("exist=" + exist);
        if (exist != null) {
            cartMapper.updateNumById(exist.getId(), exist.getNum() + 1);
        } else {
            cartMapper.insert(cart);
        }
    }

    // 更新购物车记录
    public void update(Cart cart) {
        cartMapper.updateById(cart);
    }

    // 根据 ID 删除购物车记录
    public void deleteById(Integer id) {
        cartMapper.deleteById(id);
    }


}